package com.space.school.dao.impl;

import com.space.school.dao.CategoryDao;
import com.space.school.domain.Category;
import com.space.school.domain.User;
import com.space.school.utils.SpaceJDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.*;

public class CategoryDaoImpl implements CategoryDao {
//   声明jdbc
//    获取数据库并连接
private JdbcTemplate jdbcTemplate=new JdbcTemplate(SpaceJDBCUtils.getDs());
    @Override
    public List<Category> search(int start, int pageSize, Map<String, String[]> map) {
        StringBuffer stringBuffer=new StringBuffer();
        stringBuffer.append("select * from product_category where 1=1  ");
        //        取值的集合
        ArrayList<Object> params=new ArrayList<>();
//        取map中的键的数组
        Set<String> keyset=map.keySet();
        for (String key:keyset) {
            if(!map.get(key)[0].equals("") && !key.equals("currentPage")){
                stringBuffer.append(" and " + key + " like ?");
                params.add("%"+map.get(key)[0]+"%");
            }
        }
        params.add(start);
        params.add(pageSize);
        stringBuffer.append(" order by category_id  limit ?,? ");
        return jdbcTemplate.query(stringBuffer.toString(), new BeanPropertyRowMapper<Category>(Category.class),params.toArray());
    }

    @Override
    public int count(Map<String, String[]> map) {
        StringBuffer stringBuffer=new StringBuffer();
        stringBuffer.append("select count(*) from product_category where 1=1  ");
        //        取值的集合
        ArrayList<Object> params=new ArrayList<>();
//        取map中的键的数组
        Set<String> keyset=map.keySet();
        for (String key:keyset) {
            if(!map.get(key)[0].equals("") && !key.equals("currentPage")){
                stringBuffer.append(" and " + key + " like ?");
                params.add("%"+map.get(key)[0]+"%");
            }
        }
        return jdbcTemplate.queryForObject(stringBuffer.toString(), Integer.class,params.toArray());
    }

    @Override
    public int delete(int id) {
        String sql="delete from product_category where category_id=?";
        int result=jdbcTemplate.update(sql,id);
        return result;
    }

    @Override
    public void update(Category category) {
        String sql="UPDATE product_category SET category_name = ?,category_type = ?,updateTime=? WHERE category_id = ? ";
        jdbcTemplate.update(sql,category.getCategory_name(),category.getCategory_type(),new Date(),category.getCategory_id());
    }

    @Override
    public Category findById(int id) {
        String sql = "select * from product_category where category_id=?";
        List<Category> Category=jdbcTemplate.query(sql, new BeanPropertyRowMapper<Category>(Category.class),id);
        if(Category.size()>0){
            return Category.get(0);
        }
        return null;
    }
}
